2860.
Sum of integers on the interval
Find the sum of
all integers from a to b.
Input. Two integers à and b, no more than 2 * 109 by absolute value.
Output. Print the sum
of all integers from a to b.
Sample
input |
Sample
output |
2 5 |
14 |
SOLUTION
elementary evaluations
If we calculate the result
with the loop, in the worst case (for a = -2 * 109, b = 2 * 109) we need to make up to 4 * 109
iterations, this gives Time Limit. Let’s use the formula of the sum of an
arithmetic progression. The first term equals to a, the last equas to b, and number of terms is b – a + 1. Then the required sum is
It should also
be noted that the received sum could not fit in an int. Therefore, when calculating you
should use 64-bit integer type long long.
Read the input data. Calculate and print the answer.
scanf("%lld
%lld",&a,&b);
res = (a + b) * (b - a + 1) / 2;
printf("%lld\n",res);
import
java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner con = new Scanner(System.in);
long a = con.nextLong();
long b = con.nextLong();
long res = (a + b) * (b - a + 1) / 2;
System.out.println(res);
}
}
a,b = map(int,input().split())
res = (a + b) * (b - a + 1) // 2
print (res)